/*
 * @Description: websocket处理方法
 * @Author: 梁萌
 * @Date: 2020-12-16 07:31:55
 * @LastEditTime: 2020-12-19 17:00:39
 * @FilePath: \vision\src\utils\socket_service.js
 */
export default class SocketService {
    //单例
    static instance = null;
    static get Instance() {
        if (!this.instance) {
            this.instance = new SocketService();
        }
        return this.instance;
    }


    //和服务端连接的socket对象
    ws = null;

    //存储回调函数
    callBackMapping = {};

    //是否连接成功
    connected = false;

    //记录重试连接次数
    sendRetryCount = 0;

    //重新连接尝试次数
    connectRetryCount = 0;

    //连接服务器
    connect() {
        if (!window.WebSocket) {
            return console.log('你的浏览器不支持websocket');
        }
        this.ws = new WebSocket('ws://localhost:1111');

        //连接服务器成功
        this.ws.onopen = () => {
            console.log("连接服务器成功");
            this.connected = true;

            //重置重新连接的次数
            this.connectRetryCount = 0;
        }

        //1.连接服务器失败
        //2.连接服务器成功后,服务器关闭
        this.ws.onclose = () => {
            console.log("连接服务器失败");
            this.connected = false;
            this.connectRetryCount++;
            setTimeout(() => {
                this.connect();
            }, this.connectRetryCount * 500);
        }

        //获取服务器发送过来的数据
        this.ws.onmessage = msg => {
            const recvData = JSON.parse(msg.data); //将服务器发送过来的数据转为对象
            const socketType = recvData.socketType; //获取到socketType
            //判断回调函数是否存在
            if (this.callBackMapping[socketType]) {
                const action = recvData.action; //获取到action
                if (action === 'getData') {
                    const realData = JSON.parse(recvData.data); //将图表的数据转为对象
                    this.callBackMapping[socketType].call(this, realData);
                } else if (action === 'fullScreen') {
                    this.callBackMapping[socketType].call(this, recvData);
                } else if (action === 'themeChange') {
                    this.callBackMapping[socketType].call(this, recvData);
                }
            }
        }

    }

    //回调函数的注册
    registerCallBack(socketType, callBack) {
        this.callBackMapping[socketType] = callBack;
    }


    //回调函数的注销
    unRegisterCallBack(socketType) {
        this.callBackMapping[socketType] = null;
    }


    //发送数据
    send(data) {
        if (this.connected) {
            this.sendRetryCount = 0;
            this.ws.send(JSON.stringify(data));
        } else {
            this.sendRetryCount++;
            setTimeout(() => {
                this.send(data);
            }, this.sendRetryCount * 500);
        }

    }

}